package me.zhengjie.service.impl;

import cn.hutool.core.lang.Console;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.agvSend.AgvSendService;
import me.zhengjie.mapper.LiftTaskMapper;
import me.zhengjie.pojo.dto.LiftRequestDto;
import me.zhengjie.pojo.dto.NoticeAgvDto;
import me.zhengjie.pojo.entity.LiftTask;
import me.zhengjie.service.LiftTaskService;
import me.zhengjie.sqlservilce.LiftTaskSqlService;
import me.zhengjie.state.LiftTaskStatus;
import me.zhengjie.state.TaskType;
import me.zhengjie.utils.EncryptUtil;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
* @author xinglin.lu
* @description 针对表【lift_task】的数据库操作Service实现
* @createDate 2025-08-06 13:31:11
*/
@Service
@RequiredArgsConstructor
public class LiftTaskServiceImpl extends ServiceImpl<BaseMapper<LiftTask>, LiftTask>
    implements LiftTaskService {

    private final AgvSendService agvSendService;

    private final LiftTaskMapper liftTaskMapper;

    private final LiftTaskSqlService liftTaskSqlService;

    private static final String HOST = "https://192.168.50.163:8090";
    private static final String DEVELOPER_LOGIN = "/api/cloud/base/developerLogin";
    private static final String GET_DEVICE_INFO = "/api/cloud/base/getDeviceInfo";
    private static final String URL_CALL_BACK = "/api/cloud/base/setCallbackUrl";
    private static final String URL_CALL_ELEVATOR = "/api/cloud/elevator/callNoninductiveElevator";//callElevator callNoninductiveElevator
    private static final String URL_SEND_OPEN_DOOR = "/api/cloud/elevator/sendOpenDoor";
    private static final String URL_GET_TASK_INFO = "/api/cloud/elevator/getTaskInfo";
    private static final String APP_SECRETS = "7DA51F2A61B6B79E";
    private static final String KEY = "1943490480038088705";
    private static final String AES = "0";
    private static final String SMS = "1";
    private static final String ENCRYPT_TYPE = SMS;
    private static final String DEVICE_UNIQUE = "0000664710002";
    private static final String ROBOT_ID = "000066479936";
    private static final String PROJECT_ID = "00006647";
    private static String entryDeviceUnique ="";

    public String getRequestId() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    @Override
    public void callbackUrl(String encrypt) throws Exception {
        String decrypt1 = EncryptUtil.decrypt(encrypt, APP_SECRETS, ENCRYPT_TYPE);
        JSONObject map1 = JSONObject.parseObject(decrypt1, JSONObject.class);
        if (map1 == null) {
            throw new Exception("数据为空,请检查");
        }
        JSONObject map2 = map1.getJSONObject("data");
        String requestId = (String) map2.get("requestId");
        String robotId = (String) map2.get("robotId");
        String step = (String) map2.get("step");
        System.out.println("旺龙回复数据查询参数："+requestId +"起点"+ map2.get("fromFloor") +"终点"+ map2.get("toFloor")+"step" +step);
        LiftTask liftTask = liftTaskMapper.selectOne(new LambdaQueryWrapper<LiftTask>().eq(LiftTask::getWangLongTaskIId, requestId)
                .eq(LiftTask::getStartFloor, map2.get("fromFloor"))
                .eq(LiftTask::getEndFloor, map2.get("toFloor")));
        System.out.println("旺龙数据回复:" +
                liftTask);
        if (liftTask!=null){
            if (step.equals("2")) {
                String taskCode = liftTask.getTaskCode();
                Integer id = liftTask.getId();
                //向AGV发送指令
                NoticeAgvDto noticeAgvDto = new NoticeAgvDto();
                noticeAgvDto.setEqptCode(TaskType.PAST_FLOOR.getMessage());
                noticeAgvDto.setTaskCode(taskCode);
                noticeAgvDto.setActionStatus("3");
//                boolean b = agvSendService.noticeAgv(noticeAgvDto);
                // AgvSendService.noticeAgv();
                //AGV上报到位
                boolean b1 = liftTaskSqlService.updateStatus(id, LiftTaskStatus.GET_ORDER_ENTER_LIFT.getCode());
            } else if (step.equals("4")) {
                String taskCode = liftTask.getTaskCode();
                Integer id = liftTask.getId();
                //向AGV出电梯指令
                NoticeAgvDto noticeAgvDto = new NoticeAgvDto();
                noticeAgvDto.setEqptCode(TaskType.PAST_FLOOR.getMessage());
                noticeAgvDto.setTaskCode(taskCode);
                noticeAgvDto.setActionStatus("4");
                boolean b = agvSendService.noticeAgv(noticeAgvDto);
                // AgvSendService.noticeAgv();
                boolean b1 = liftTaskSqlService.updateStatus(id, LiftTaskStatus.GET_ORDER_LEAVE_LIFT.getCode());
                //向AGV发送指令
                // AgvSendService.noticeAgv();
                //任务完成
            }
//        baseMapper.updateById(liftTask);
        }
    }

    @Override
    public String sendOpenDoor(LiftRequestDto liftRequestDto) throws Exception {
        JSONObject json = JSON.parseObject(getToken());
        json = json.getJSONObject("data");
        //
        JSONObject data = new JSONObject();
        data.put("requestId", liftRequestDto.getRequestId());
        data.put("timestamp", (new Date()).getTime() + "");
        data.put("robotId", ROBOT_ID);
//        data.put("deviceUnique", entryDeviceUnique);
        data.put("deviceUnique", DEVICE_UNIQUE);
        data.put("effectiveTime", liftRequestDto.getEffectiveTime());
        data.put("position", liftRequestDto.getPosition());//in|out
        data.put("appCode", "01014V3");
        //
        String encryptScript = EncryptUtil.encrypt(JSONObject.toJSONString(data), APP_SECRETS, ENCRYPT_TYPE);
        json.put("encryptScript", encryptScript);
        //
        String str = HttpUtil.post(HOST + URL_SEND_OPEN_DOOR, json);
        JSONObject result = JSON.parseObject(str);
        encryptScript = result.getString("encryptScript");
        String decrypt1 = EncryptUtil.decrypt(encryptScript, APP_SECRETS, ENCRYPT_TYPE);
        Console.log("sendOpenDoor接口结果", decrypt1);
        return decrypt1;
    }

    @Override
    public String developerLogin(String robotId) throws Exception {
        JSONObject t = new JSONObject();
        t.put("requestId", "ea0a3cef18c45e769f7136de7977db3f");
        t.put("robotId", robotId);
        t.put("projectId", PROJECT_ID);
        String data = t.toJSONString();
        JSONObject json = JSON.parseObject(data);
        json.put("timestamp", (new Date()).getTime() + "");
        String s = EncryptUtil.getSDKV3Sign(json, APP_SECRETS, ENCRYPT_TYPE);
        Console.log("1.加签结果:", s);

        json.put("sign", s);
        String encryptScript = EncryptUtil.encrypt(json.toString(), APP_SECRETS, ENCRYPT_TYPE);
        Console.log("2.加密结果:", encryptScript);

        Map<String, Object> map = new HashMap<>();
        map.put("appId", KEY);
        map.put("encryptScript", encryptScript);
        map.put("encryptType", ENCRYPT_TYPE);
        String str = HttpUtil.post(HOST + DEVELOPER_LOGIN, map);
        Console.log("3.SDK认证结果", str);

        JSONObject result = JSON.parseObject(str);
        encryptScript = result.getString("encryptScript");
        String decrypt = EncryptUtil.decrypt(encryptScript, APP_SECRETS, ENCRYPT_TYPE);
        Console.log("4.SDK认证解密结果", decrypt);
        return decrypt;
    }

    @Override
    public String callElevator(LiftRequestDto liftRequestDto) throws Exception {
        JSONObject json = JSON.parseObject(getToken());
        json = json.getJSONObject("data");
        //
        JSONObject data = new JSONObject();
        data.put("requestId", liftRequestDto.getRequestId());
        data.put("timestamp", (new Date()).getTime() + "");
        data.put("robotId", ROBOT_ID);
        data.put("deviceUnique", DEVICE_UNIQUE);
        data.put("fromFloor", liftRequestDto.getFromFloor());
        data.put("toFloor", liftRequestDto.getToFloor());
//        data.put("openTime", "20");
        data.put("openTime", liftRequestDto.getOpenTime());
        data.put("appCode", "01014V3");
        //
        Console.log("时间戳:{}", JSONObject.toJSONString(data));
        String encryptScript = EncryptUtil.encrypt(JSONObject.toJSONString(data), APP_SECRETS, ENCRYPT_TYPE);
        json.put("encryptScript", encryptScript);
        //
        String str = HttpUtil.post(HOST + URL_CALL_ELEVATOR, json);
        JSONObject result = JSON.parseObject(str);
        encryptScript = result.getString("encryptScript");
        String decrypt1 = EncryptUtil.decrypt(encryptScript, APP_SECRETS, ENCRYPT_TYPE);
        Console.log("callElevator接口结果", decrypt1);
        //存数据库
//        LiftTask liftTask = new LiftTask();
//        liftTask.setTaskCode(data.getString("requestId"));
//        liftTask.setStartFloor(data.getString("fromFloor"));
//        liftTask.setEndFloor(data.getString("toFloor"));
//        liftTask.setStatus("0");
//        liftTask.setCreateTime(LocalDateTime.now());

        return decrypt1;
    }

    @Override
    public String setCallBack(LiftRequestDto liftRequestDto) throws Exception {
        JSONObject json = JSON.parseObject(getToken());
        json = json.getJSONObject("data");
        //
        JSONObject data = new JSONObject();
        data.put("requestId", getRequestId());
        data.put("timestamp", (new Date()).getTime() + "");
        data.put("robotId", ROBOT_ID);
        data.put("url", "http://192.168.52.198:8008/lift/callback/url");
//        data.put("url", "http://192.168.53.76:8008");
        data.put("type", "1");
        data.put("status", "1");
        data.put("version", "1");
        data.put("appCode", "01014V3");

        //
        Console.log("时间戳:{}", JSONObject.toJSONString(data));
        String encryptScript = EncryptUtil.encrypt(JSONObject.toJSONString(data), APP_SECRETS, ENCRYPT_TYPE);
        json.put("encryptScript", encryptScript);
        //
        String str = HttpUtil.post(HOST +URL_CALL_BACK, json);
        JSONObject result = JSON.parseObject(str);
        encryptScript = result.getString("encryptScript");
        String decrypt1 = EncryptUtil.decrypt(encryptScript, APP_SECRETS, ENCRYPT_TYPE);
        Console.log("callElevator接口结果", decrypt1);
        return decrypt1;
    }

    public static String getToken() throws Exception {
        JSONObject t = new JSONObject();
        t.put("requestId", "ea0a3cef18c45e769f7136de7977db3f");
        t.put("robotId", ROBOT_ID);
        t.put("projectId", PROJECT_ID);
        String data = t.toJSONString();
        JSONObject json = JSON.parseObject(data);
        json.put("timestamp", (new Date()).getTime() + "");
        String s = EncryptUtil.getSDKV3Sign(json, APP_SECRETS, ENCRYPT_TYPE);
        Console.log("1.加签结果:", s);

        json.put("sign", s);
        String encryptScript = EncryptUtil.encrypt(json.toString(), APP_SECRETS, ENCRYPT_TYPE);
        Console.log("2.加密结果:", encryptScript);

        Map<String, Object> map = new HashMap<>();
        map.put("appId", KEY);
        map.put("encryptScript", encryptScript);
        map.put("encryptType", ENCRYPT_TYPE);
        String str = HttpUtil.post(HOST + DEVELOPER_LOGIN, map);
        Console.log("3.SDK认证结果", str);

        JSONObject result = JSON.parseObject(str);
        encryptScript = result.getString("encryptScript");
        String decrypt = EncryptUtil.decrypt(encryptScript, APP_SECRETS, ENCRYPT_TYPE);
        Console.log("4.SDK认证解密结果", decrypt);

        return decrypt;
    }

}




